<script setup lang="ts">
  import qs from 'qs';
  import { ElTree } from 'element-plus';
  import { getGroupRemove } from '@/api/userChoice';
  import { useRoute } from 'vue-router';
  const route = useRoute();
  const treeRef = ref<InstanceType<typeof ElTree>>();
  const treeExpandData = ref<Array<string>>([]);
  const iconArray = ref<Array<Namespace.unitIconSzie>>();
  const showRightMenu = ref<boolean>(false);
  const hasParent = ref<boolean>(false);
  const childrenData = ref<any>();
  const EmitsData = ref<Array<Namespace.unitTree> | Array<Namespace.commandRegion>>();
  const props = defineProps({
    data: {
      type: Array,
    },
    id: {
      type: String,
      delault: '',
    },
    icons: {
      type: Boolean,
      delault: false,
    },
    iconsData: {
      type: Array,
    },
    rightMenuList: {
      type: Array<Namespace.unitRightMenu>,
    },
    menuShow: {
      type: Boolean,
      delault: false,
    },
    selected: {
      type: Object,
      default: () => {},
    },
    dataTree: {
      type: String,
      default: '',
    },
    isCommpand: {
      type: Boolean,
      default: false,
    },
    islower: {
      type: Boolean,
      default: false,
    },
    isUser: {
      type: Boolean,
      default: false,
    },
  });

  const nodePops = {
    value: 'id',
    label: 'text' || 'permissionName' || 'groupName',
    children: 'children',
  };
  const idSave = ref<string>('');

  watch(
    () => props,
    async (val: any) => {
      if (val?.id == '' || val?.id) {
        treeRef.value?.filter(val.id);
      }
      if (val.data) {
        if (!props.selected) {
          treeExpandData.value = [val.data[0].id];
        } else {
          if (typeof val.selected == 'string') {
            treeExpandData.value = [val.selected];
          } else {
            treeExpandData.value = [val.selected.id];
          }
        }
      }
      if (val.dataTree) {
        treeExpandData.value = [val.dataTree];
      }
      if (val.iconsData?.length) {
        iconArray.value = val.iconsData as Array<Namespace.unitIconSzie>;
      }
      if (val.islower) {
        treeExpandData.value = [val.data[0].id];
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );
  const filterNode = (value: string, data: any) => {
    if (!value) return true;
    // return data.id.includes(value);
    return data.id == value;
  };
  const rightClick = async (event, data) => {
    if (props.isUser) return;
    showRightMenu.value = true;
    let menu = document.querySelector('.rightMenu') as HTMLDivElement;
    menu.style.left = event.clientX + 'px';
    if (event.clientY > 561) {
      if (route.name == 'sourceDataManage') {
        menu.style.top = event.clientY - 130 + 'px';
      } else {
        menu.style.top = event.clientY - 230 + 'px';
      }
    } else {
      menu.style.top = event.clientY + 'px';
    }
    EmitsData.value = data;
    if (data.parentId != '') {
      hasParent.value = false;
    } else {
      hasParent.value = true;
    }
    showRightMenu.value = true;
    document.addEventListener('click', show);
  };

  const sendGrandson = inject('sendHandle') as Function;
  const sendGrandsonSelectCommand = inject('sendHandleSelectCommand') as Function;
  const sendGrandsonSelectUser = inject('sendHandleSelectUser') as Function;
  const handleNodeClick = async (data) => {
    if (props.islower) {
      sendGrandsonSelectCommand(data);
    } else if (props.isUser) {
      sendGrandsonSelectUser(data);
    } else {
      sendGrandson(data);
      idSave.value = data;
    }
    childrenData.value = data;
  };
  const show = () => {
    showRightMenu.value = false;
  };
  const handleDelete = async () => {
    const data = {
      id: childrenData.value.id,
    };
    const { code } = await getGroupRemove(qs.stringify(data));
    if (code == 0) {
      sendGrandsonRemove(true);
    }
  };
  const sendGrandsonRemove = inject('sendHandleRemove') as Function;
</script>

<template>
  <div class="treeComponents">
    <ElTree
      ref="treeRef"
      class="tree"
      :data="props.data"
      :props="nodePops"
      node-key="id"
      :highlight-current="true"
      :default-expanded-keys="treeExpandData"
      @node-click="handleNodeClick"
      @node-contextmenu="rightClick"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :style="{
        height: isCommpand ? 'calc(100vh - 120px)' : islower ? '' : 'calc(100vh - 156px)',
      }"
    >
      <template #default="{ data }" v-if="props.icons">
        <template v-for="item in iconArray" :key="item.name">
          <template v-if="data.icon == item.name">
            <svgIcon :color="item.color" :name="item.name" :size="item.size" />
            <span class="treeIcons">{{ data.text }}</span>
          </template>
        </template>
      </template>
      <template #default="{ data }" v-else>
        <div
          v-if="data.groupName"
          style="display: flex; width: 100%; justify-content: space-between; align-items: center"
        >
          <span
            class="treeIconsText"
            :style="{
              paddingLeft: props.isUser ? '0' : '20px',
              marginLeft: props.isUser ? '0' : '5px',
            }"
            >{{ data.permissionName || data.text || data.groupName }}</span
          >
          <template v-if="data.groupName">
            <SvgIcon
              @click="handleDelete"
              style="cursor: pointer; position: relative; z-index: 999"
              name="jstree-delete"
            />
          </template>
        </div>
        <span
          class="treeIconsText"
          v-else
          :style="{
            paddingLeft: props.isUser ? '0' : '20px',
            marginLeft: props.isUser ? '0' : '5px',
          }"
          >{{ data.permissionName || data.text }}</span
        >
      </template>
    </ElTree>
    <template v-if="props.menuShow">
      <div class="rightMenu" v-show="showRightMenu">
        <ul>
          <template v-for="item in props.rightMenuList" :key="item.iconName">
            <li
              v-if="
                (item.iconName == 'jstree-group' ||
                  item.iconName == 'jstree-export' ||
                  item.iconName == 'jstree-import') &&
                !hasParent
              "
              style="cursor: not-allowed"
            >
              <SvgIcon color="#606266" :name="item.iconName" :size="item.size" />
              <span style="color: var(--el-text-color-regular)">{{ item.name }}</span>
            </li>
            <li v-else @click="item.function(EmitsData, idSave)">
              <SvgIcon :name="item.iconName" :size="item.size" />
              <span>{{ item.name }}</span>
            </li>
          </template>
        </ul>
      </div>
    </template>
  </div>
</template>

<style lang="scss">
  .treeComponents {
    position: relative;
    margin-top: 10px;
    .tree {
      overflow-x: hidden;
    }
    .treeIcons {
      // width: 165px;
      flex: 1;
      margin-left: 5px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      -o-text-overflow: ellipsis;
    }
    .treeIconsText {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      -o-text-overflow: ellipsis;
    }
    .rightMenu {
      height: auto;
      position: fixed;
      z-index: 99999999;
      background: var(--el-fill-color-extra-light);
      border: 1px solid var(--el-color-info-light-3);
      box-shadow: 2px 2px 2px var(--el-color-info);
      padding: 2px;
      width: 160px;
      border-radius: 3px;
      overflow: hidden;
      ul {
        list-style: none;
        margin: 0;
        padding: 0;
        border-radius: 6px;
        li {
          cursor: pointer;
          padding: 10px 10px;
          background: #fff;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          .svg-icon {
            width: 20% !important;
          }
          span {
            padding-left: 20px;
            width: 80%;
            font-size: 14px;
          }
        }
        li:last-child {
          border: none;
        }
      }
      li:hover {
        transition: all 1s;
        position: relative;
        background-color: var(--el-fill-color-lighter);
        box-shadow: 0 0 2px var(--el-color-primary);
      }
    }
    .rightMenu::after {
      position: absolute;
      content: '';
      width: 1px;
      height: $height;
      background: #ccc;
      top: 0;
      left: 40px;
    }
  }
  .tree .el-tree-node {
    position: relative;
    // padding-left: 16px;
  }
  .tree .el-tree-node__children {
    padding-left: 16px;
  }

  .tree .el-tree-node :last-child:before {
    height: 38px;
  }
  .tree .el-tree > .el-tree-node:before {
    border-left: none;
  }
  .tree-container .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .tree .el-tree-node__children .el-tree-node:before {
    content: '';
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .tree .el-tree-node:after {
    content: '';
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }
  .tree .el-tree-node__expand-icon.is-leaf {
    display: none;
  }

  .tree .el-tree-node:before {
    border-left: 1px dashed var(--el-text-color-placeholder);
    bottom: 0px;
    height: 100%;
    top: -26px;
    width: 1px;
  }

  .tree .el-tree-node:after {
    border-top: 1px dashed var(--el-text-color-placeholder);
    height: 20px;
    top: 12px;
    width: 24px;
  }
  .tree .custom-tree-node {
    padding-left: 10px;
  }
</style>
